<?php
// +----------------------------------------------------------------------
// | Created by Sublime: [ Conqweal ]
// +----------------------------------------------------------------------
// | Copyright (c) 2021~20223[chenjia] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.99dn.cn
// +----------------------------------------------------------------------
// | Author: Conqweal <150672834@qq.com>
// +----------------------------------------------------------------------
// | Date: 2021/12/22 0026
// +----------------------------------------------------------------------
// | Description:充值提现管理
// +----------------------------------------------------------------------


namespace app\admin\controller;

use app\admin\model\UserCashRar as cmodel;
use think\facade\Cache;
use support\Request;
use think\facade\Db;
use app\BackendController;

class CashRarController extends BackendController
{
    /**
     * 充值提现列表
     *
     * @return \think\Response
     */
    public function index()
    {

        //支付状态
        $tmp              = cmodel::getPayFlag();
        $pay_flag_options = output_select($tmp, []);
        //审核状态
        $tmp                = cmodel::getCheckFlag();
        $check_flag_options = output_select($tmp, []);
        //过帐类型
        $tmp          = cmodel::getType();
        $type_options = output_select($tmp, []);

        return view('cashrar/index', compact('pay_flag_options', 'check_flag_options', 'type_options'));
    }

    /**
     * 列表json数据
     * @param  Request $request [请求变量]
     * @return [type]           [json数据]
     */
    public function listData(Request $request)
    {
        $limit = $request->get('limit', 10);
        $w     = [];

        if ($request->get('remark')) {
            $w[] = ['a.remark', 'like', '%' . $request->get('remark') . '%'];

        }

        if ($request->get('u_id')) {
            $w[] = ['a.u_id', '=', $request->get('u_id')];

        }

        if ($request->get('pay_flag')!=null) {
            $w[] = ['a.pay_flag', '=', $request->get('pay_flag')];

        }

        if ($request->get('check_flag')!=null) {
            $w[] = ['a.check_flag', '=', $request->get('check_flag')];

        }
        if ($request->get('type')) {
            $w[] = ['a.type', '=', $request->get('type')];

        }

        $q = cmodel::alias('a')->where($w)->order("id desc");

        $ls         = $q->paginate(['list_rows' => $limit, 'request' => $request->all()]);
        $res        = $ls->items();
        $pay_flag   = cmodel::getPayFlag();
        $check_flag = cmodel::getCheckFlag();
        $type       = cmodel::getType();
        $res        = array_map(function ($v) use ($pay_flag, $check_flag, $type) {
            $v->pay_flag_txt   = $pay_flag[$v->pay_flag];
            $v->type_txt       = $type[$v->type];
            $v->check_flag_txt = $check_flag[$v->check_flag];
            $v->user_info      = $v->user_info;
            $v->profile        = $v->user_info->profile;
            return $v;
        }, $res);

        return json(['code' => $ls->total() > 0 ? 0 : 201, 'msg' => '无数据', 'count' => $ls->total(), 'data' => $res]);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit(Request $request)
    {
        $id = $request->get("id");
        $data = cmodel::find($id);
        //审核状态
        $tmp = cmodel::getCheckFlag();

        $check_flag_options = output_select($tmp, $data->check_flag);
        //支付状态
        $tmp = cmodel::getPayFlag();

        $pay_flag_options = output_select($tmp, $data->pay_flag);

        return view('cashrar/edit', compact('data', 'check_flag_options', 'pay_flag_options'));
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request)
    {
        $id  = $request->get("id");
        $post  = $request->post();
        $valid = new \app\admin\validate\CashRar;
        $r     = $valid->check($post);

        $cmodel = new cmodel;
        $info   = $cmodel->where('id', $id)->where('type',2)->find();
        if (!$r) {
            $data = ['status' => -1, 'msg' => $valid->getError()];
        } else {
            Db::startTrans();
            try {
                if ($info->check_flag == 1) {
                    throw new \Exception(__("Approved and cannot be modified"), 1);
                }
                $post['pay_flag'] =1;
                $info->allowField(['pay_flag', 'check_flag'])->save($post);
                //处理积分
                $f = Db::name('user_money_log')->where("op_type", $info['type'])->where("op_key", $id)->find();
                if ($post['check_flag'] == 1  && !$f) {
                    $this->dealMoney($info);
                }

                $data = ['status' => 1, 'msg' => '保存成功'];

                Db::commit();
            }  catch (\Exception $e) {
                Db::rollback();
                $data['msg'] = $e->getMessage();
            }

        }
        return json($data);

    }

    private function dealMoney($info)
    {

        $plus      = 0;
        $reduce    = $info['money'];
        $blance    = \app\admin\model\User::find($info['u_id']);
        $before    = $blance['money'];
        $after     = $before + $plus - $reduce;
        $log_model = new \app\admin\model\UserMoneyLog;
        $log_model->save([
            'op_type' => $info['type'],
            'op_key'  => $info['id'],
            'u_id'    => $info['u_id'],
            'plus'    => $plus,
            'reduce'  => $reduce,
            'before'  => $before,
            'after'   => $after,

        ]
        );

        //冻结减少
        if ($blance['money'] < $reduce) {
            throw new \Exception(__("Insufficient balance, unable to withdraw cash"), 1);

        }
        $blance->dec('money', $reduce)->dec('freeze', $reduce)->update();

    }

}